package com.lagou.common;

import com.lagou.pojo.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.ByteBuffer;
import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {
    private final Class<?> clazz;
    private final Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int dataLength = in.readInt();

        //读取完整的消息体字节数组
        byte[] data = new byte[dataLength];
        in.readBytes(data);

        RpcRequest request = (RpcRequest) serializer.deserialize(clazz, data);
        out.add(request);
    }


}
